package com.dy.vueadminservice.config;

import com.dy.vueadminservice.exception.OAuth2WebResponseExceptionTranslator;
import com.dy.vueadminservice.service.users.impl.UserInfoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * 认证服务器配置
 *
 * @author huangdeyao
 * @date 2019/1/8 12:47
 * //加上这句注解就已经实现了认证服务器
 * EnableAuthorizationServer
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserInfoServiceImpl userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private OAuth2WebResponseExceptionTranslator oauth2WebResponseExceptionTranslator;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore);
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
        // 处理 ExceptionTranslationFilter 抛出的异常
        endpoints.exceptionTranslator(oauth2WebResponseExceptionTranslator);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("devglan-client")
                .secret(passwordEncoder.encode("devglan-secret"))
                .accessTokenValiditySeconds(30 * 24 * 3600)
                .authorizedGrantTypes("refresh_token", "password")
                .scopes("all", "read", "write");
    }
}
